﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;

namespace QbiconEditor
{
    public partial class QbiconForm : Form
    {
        private enum MouseAction { MA_Selection, MA_OnPoints, MA_OnObjects, MA_OnLine, MA_Nothing };
        private enum WheelAction { MW_Zoom, MW_Scale, MW_Rotate };

        private MouseAction currentMouseAction = MouseAction.MA_Nothing;
        private WheelAction currentWheelAction = WheelAction.MW_Zoom;
        private QPoint[] lastHighlightedLine = null;
        
        private Point mousePreviousPos = new Point(0,0);
        private Graphics currentOutput;
        private Graphics drawTo;
        private IQRender CurrentRender;
        private QRectangleF selectionRect = new QRectangleF() {Left = 0, Top = 0, Width = 0, Height = 0};
        private Bitmap tmpsurface;
        
        private bool objectActivationByProgram = false;

        public static void SetDoubleBuffered(Control control)
        {
          // set instance non-public property with name "DoubleBuffered" to true
          typeof(Control).InvokeMember("DoubleBuffered",
               BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
               null, control, new object[] { true });
        }

        public QbiconForm()
        {
            InitializeComponent();
            
            drawTo = drawPanel.CreateGraphics();
            tmpsurface = new Bitmap(drawPanel.Width, drawPanel.Height);
            currentOutput = Graphics.FromImage(tmpsurface);
            
            QGraphicsHelper.Preferences = new QPreferences();  
            QPreferences prf = QHelper.LoadPreferences("default.qpr");

            if (prf != null)
            {
                QGraphicsHelper.Preferences = prf;
            }

            QGraphicsHelper.ZoomAspect = 50;
            CurrentRender = new QStandartRender();

            NewMap();

            this.WindowState = FormWindowState.Maximized;
            this.texturesListView.LargeImageList = QGraphicsHelper.Textures.ThumbnailsList;
        }

        private void SetWheelAction(WheelAction action)
        {
          scaleToolStripMenuItem.Checked = false;
          rotateToolStripMenuItem.Checked = false;
         
          currentWheelAction = action;

          if (action == WheelAction.MW_Scale)
          {
            scaleToolStripMenuItem.Checked = true;
          }
          else if (action == WheelAction.MW_Rotate)
          {
            rotateToolStripMenuItem.Checked = true;
          }
        }

        private void SetActiveQObject(QObject qob)
        {
          if (qob != null)
          {
            objectActivationByProgram = true;
            comboBox1.SelectedItem = qob;
            objectActivationByProgram = false;

            if (QHelper.CurrentWorkQItem.selectedObjects.Contains(qob) == false)
            {
              QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
            }
          }
          else
          {
            objectActivationByProgram = true;
            comboBox1.SelectedItem = null;
            comboBox1.Text = "";
            objectActivationByProgram = false;
          }

          propertyGrid1.SelectedObject = qob;

          RenderAll();
        }

        private void setStatusLabelInfo()
        {
          QPoint mp = QGraphicsHelper.GetPointOnMap(mousePreviousPos.X, mousePreviousPos.Y);
          StatusLabel1.Text = string.Format("[{2} : {3}   {4} : {5}]   |   {0} : {1}   |  [{6} : {7}   {8} : {9} |",
                                  new string[] {mp.X.ToString(),
                                                  mp.Y.ToString(),
                                                  QGraphicsHelper.ViewRect.Left.ToString(),
                                                  QGraphicsHelper.Preferences.TopOnBottom ? QGraphicsHelper.ViewRect.Top.ToString() : (-QGraphicsHelper.ViewRect.Top).ToString(),
                                                  QGraphicsHelper.ViewRect.Width.ToString(),
                                                  QGraphicsHelper.ViewRect.Height.ToString(),
                                                  selectionRect.Top.ToString(),
                                                  selectionRect.Left.ToString(),
                                                  selectionRect.Width.ToString(),
                                                  selectionRect.Height.ToString()

                                  });
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
          if (objectActivationByProgram == false)
          {
            QHelper.CurrentWorkQItem.selectedObjects.Clear();
            QHelper.CurrentWorkQItem.selectedPoints.Clear();
            SetActiveQObject(comboBox1.SelectedItem as QObject);
            QGraphicsHelper.NavigateToObject(comboBox1.SelectedItem as QObject);

            RenderAll();
          }
        }
        
        private void FindSelectedObjects()
        {
          QHelper.CurrentWorkQItem.selectedPoints.Clear();
          QHelper.CurrentWorkQItem.selectedPoints.AddRange(QHelper.FindPointsInRect(selectionRect));

          foreach (QPoint qp in QHelper.CurrentWorkQItem.selectedPoints)
          {
            QObject qob = QHelper.GetPointParentObject(qp);

            if (qob != null && QHelper.CurrentWorkQItem.selectedObjects.Contains(qob) == false)
            {
              QHelper.CurrentWorkQItem.selectedObjects.Insert(0, qob);
            }
          }

          if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
          {
            SetActiveQObject(QHelper.CurrentWorkQItem.selectedObjects[0]);
          }
        }

        private void RenderSelectionRect()
        {

          Rectangle r = QGraphicsHelper.FixRectangle(QGraphicsHelper.GetRectOnScreen(selectionRect));

          if (currentOutput != null)
          {
            Pen p = new Pen(QGraphicsHelper.Preferences.SelectionRectColor, QGraphicsHelper.Preferences.SelectionRectPenWidth);
            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;

            currentOutput.DrawRectangle(p, r);
          }
        }

        private bool CheckAndDrawIfMouseOnLines(int mX, int mY)
        {
          QPoint pointOnMap = QGraphicsHelper.GetPointOnMap(mX, mY);

          RectangleF rect = QGraphicsHelper.GetFrameRectInPoint(new QPoint() { X = mX, Y = mY }, QGraphicsHelper.Preferences.PointFrameRectWidth);
         
          // currentOutput.DrawRectangle(new Pen(Color.Black), rect.X, rect.Y, rect.Width, rect.Height);
          
          if (lastHighlightedLine != null)
          {
            if (QHelper.GetAllObjectsPoints(QHelper.CurrentWorkQItem.selectedObjects.ToArray()).Contains(lastHighlightedLine[0]) == true)
            {
              CurrentRender.RenderLineOnScreen(lastHighlightedLine[0], lastHighlightedLine[1], currentOutput, QGraphicsHelper.Preferences.ActiveObjectFrameColor, QGraphicsHelper.Preferences.FrameRectPenWidth);
              CurrentRender.RenderRectPoints(lastHighlightedLine.ToArray(), currentOutput, QGraphicsHelper.Preferences.ActiveObjectFrameColor);
              CurrentRender.RenderRectPoints(QHelper.CurrentWorkQItem.selectedPoints.ToArray(), currentOutput, QGraphicsHelper.Preferences.ActivePointFrameColor);
            }
          }

          foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
          {
            QPoint[] points = QGraphicsHelper.IsRectInLinesBetweenPoints(rect, qob.Poly.Points.ToArray(), true);
            
            if (points != null && QGraphicsHelper.IsPointInCornerRects(points, QGraphicsHelper.GetPointOnScreen(pointOnMap)) == null)
            {
              CurrentRender.RenderActiveObject(qob, currentOutput, true);
              CurrentRender.RenderRectPoints(points, currentOutput, QGraphicsHelper.Preferences.ActivePointFrameColor);
              CurrentRender.RenderLineOnScreen(points[0], points[1], currentOutput, QGraphicsHelper.Preferences.ActivePointFrameColor, QGraphicsHelper.Preferences.FrameRectPenWidth);
              lastHighlightedLine = points;

              return true;
            }
          }

          lastHighlightedLine = null;

          return false;
        }

        private void RenderAll()
        {
          bool drawCorners = (selectionRect.Width != 0 || selectionRect.Height != 0);

          if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
          {
            CurrentRender.RenderMap(QHelper.CurrentMap, currentOutput, null, QHelper.CurrentWorkQItem.selectedObjects, QGraphicsHelper.Preferences.UseTextures, false);
            
            foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
            {
              CurrentRender.RenderActiveObject(qob, currentOutput, true);
            }
          }
          else
          {
              CurrentRender.RenderMap(QHelper.CurrentMap, currentOutput, null, null, QGraphicsHelper.Preferences.UseTextures, false);
          }

          if (drawCorners)
          {
              CurrentRender.RenderLayer(QHelper.CurrentLayer, currentOutput, null, QGraphicsHelper.Preferences.UseTextures, drawCorners);
          }

          if (QHelper.CurrentWorkQItem.selectedPoints.Count > 0)
          {
           // QRender.RenderMap(currentMap, currentOutput, selectedObjects, true);
              CurrentRender.RenderRectPoints(QHelper.CurrentWorkQItem.selectedPoints.ToArray(), currentOutput, QGraphicsHelper.Preferences.ActivePointFrameColor);
          }

          if (lastHighlightedLine != null)
          {
              CurrentRender.RenderLineOnScreen(lastHighlightedLine[0], lastHighlightedLine[1], currentOutput, QGraphicsHelper.Preferences.ActivePointFrameColor, QGraphicsHelper.Preferences.FrameRectPenWidth);
          }

          if (QGraphicsHelper.Preferences.ShowGrid == true)
          {
              CurrentRender.RenderGrid(currentOutput, QGraphicsHelper.Preferences.GridCellSize);
          }

          if (QGraphicsHelper.Preferences.ShowAxes == true)
          {
            CurrentRender.RenderAxes(currentOutput);
          }

          RenderSelectionRect();

          if (QGraphicsHelper.Preferences.ShowPointsHints == true)
          {

            foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
            {
              CurrentRender.RenderPointsHints(qob.Poly, currentOutput);
            }

            //QPolygone poly = new QPolygone();
            //poly.Points.AddRange(selectedPoints.ToArray());
            //QRender.RenderPointsHints(poly, currentOutput);
          }

          //draw to form
          drawTo.DrawImage(tmpsurface, 0, 0);

          setStatusLabelInfo();
        }

        private void drawPanel_Paint(object sender, PaintEventArgs e)
        {
            RenderAll();   
        }

        private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            if (propertyGrid1.SelectedObject is QObject) 
            {
                if (e.ChangedItem.Label == "Name")
                {
                  QObject qob = propertyGrid1.SelectedObject as QObject;
                  string nn = e.ChangedItem.Value.ToString();

                  qob.Name = e.OldValue.ToString();

                  if (QHelper.FindFreeObjectName(nn) == nn)
                  {
                    qob.Name = nn;
                    comboBox1.Items.Remove(qob);
                    comboBox1.Items.Add(qob);
                    comboBox1.SelectedItem = qob;
                  }
                  else
                  {
                    (propertyGrid1.SelectedObject as QObject).Name = e.OldValue.ToString();
                  }
                }
            }

            if (propertyGrid1.SelectedObject is QMapLayer)
            {
              if (e.ChangedItem.Label == "Name")
              {
                FillLayersMenuFromCurrentMap();
              }
            }

            if (propertyGrid1.SelectedObject is QPreferences)
            {
              if (e.ChangedItem.Label == "UseTextures")
              {
                  useTexturesMenuItem.Checked = QGraphicsHelper.Preferences.UseTextures;
              }
            }

            RenderAll();
        }

        private void changeSelectedObjectsPoints(float dx, float dy)
        {
          foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
          {
            QHelper.ChangeObjectPoints(qob, dx, dy);
          }
        }

        private void drawPanel_MouseDown(object sender, MouseEventArgs e)
        {
          drawPanel.Focus();

          if (e.Button == MouseButtons.Left)
          {
              QPoint mapPoint = QGraphicsHelper.GetPointOnMap(e.X, e.Y);
              QPoint scrPoint = QGraphicsHelper.GetPointOnScreen(mapPoint);
  
            //check if mouse is not in selected points
            QPoint qp = QGraphicsHelper.IsPointInCornerRects(QHelper.CurrentWorkQItem.selectedPoints.ToArray(), scrPoint);
            
            if (qp == null)
            {
              //check if mouse on line between points
              if (CheckAndDrawIfMouseOnLines(e.X, e.Y) == false)
              {
                //check if mouse is not in all objects corner points
                QObject qob = QGraphicsHelper.IsPointInCornersOfObjects(QHelper.CurrentLayer.Objects, scrPoint.X, scrPoint.Y);
                
                if (qob == null)
                {
                  //check if mouse is not in polygones of selected objects
                  qob = QGraphicsHelper.IsPointInObjects(QHelper.CurrentWorkQItem.selectedObjects, mapPoint.X, mapPoint.Y);
                  
                  if (qob == null)
                  {
                    // check if mouse is not in polygones of all objects
                    qob = QGraphicsHelper.IsPointInObjects(QHelper.CurrentLayer.Objects, mapPoint.X, mapPoint.Y);
                    
                    if (qob == null)
                    {
                      //mouse in empty space!!! start selection :)
                      QHelper.CurrentWorkQItem.selectedObjects.Clear();
                      QHelper.CurrentWorkQItem.selectedPoints.Clear();

                      SetActiveQObject(null);
                      selectionRect.Left = mapPoint.X;
                      selectionRect.Top = mapPoint.Y;
                      currentMouseAction = MouseAction.MA_Selection;
                      SetWheelAction(WheelAction.MW_Zoom);
                    }
                    else
                    {
                      //mouse in body of unselected object
                      QHelper.CurrentWorkQItem.selectedObjects.Clear();
                      QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
                      QHelper.CurrentWorkQItem.selectedPoints.Clear();
                      QHelper.CurrentWorkQItem.selectedPoints.AddRange(qob.Poly.Points);

                      SetActiveQObject(qob);
                      currentMouseAction = MouseAction.MA_OnObjects;
                    }
                  }
                  else
                  {
                    //mouse in one of selected object, maybe user want to move it
                    SetActiveQObject(qob);
                    currentMouseAction = MouseAction.MA_OnObjects;
                  }
                }
                else
                {
                  //mouse in corner points of not selected object, select him
                  QHelper.CurrentWorkQItem.selectedObjects.Clear();
                  QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
                  QHelper.CurrentWorkQItem.selectedPoints.Clear();
                  QHelper.CurrentWorkQItem.selectedPoints.Add(QGraphicsHelper.IsPointInCornersOfObject(qob, scrPoint.X, scrPoint.Y));
                  SetActiveQObject(qob);
                  if (QHelper.CurrentWorkQItem.selectedPoints.Count > 0)
                  {
                    propertyGrid1.SelectedObject = QHelper.CurrentWorkQItem.selectedPoints[0];
                  }
                  currentMouseAction = MouseAction.MA_OnPoints;
                }
              }
              else
              {
                QHelper.CurrentWorkQItem.selectedPoints.Clear();
                QHelper.CurrentWorkQItem.selectedPoints.AddRange(lastHighlightedLine);
                currentMouseAction = MouseAction.MA_OnLine;
              }
            }
            else
            {
              //Mouse in some of selected points
              currentMouseAction = MouseAction.MA_OnPoints;
            }
          }

          mousePreviousPos = new Point(e.X, e.Y);
        }

        private void drawPanel_MouseMove(object sender, MouseEventArgs e)
        {
            float deltaX = (mousePreviousPos.X - e.X) / QGraphicsHelper.ZoomAspect;
            float deltaY = (mousePreviousPos.Y - e.Y) / QGraphicsHelper.ZoomAspect;
            int deltaXint = (mousePreviousPos.X - e.X);
            int deltaYint = (mousePreviousPos.Y - e.Y);

            deltaY = QGraphicsHelper.Preferences.TopOnBottom ? deltaY : -deltaY;
            deltaYint = QGraphicsHelper.Preferences.TopOnBottom ? deltaYint : -deltaYint;
            QPoint mapPoint = QGraphicsHelper.GetPointOnMap(e.X, e.Y);

            drawPanel.Cursor = Cursors.Arrow;

            if (e.Button == MouseButtons.None)
            {
              if (QGraphicsHelper.IsPointInCornersOfObjects(QHelper.CurrentWorkQItem.selectedObjects, e.X, e.Y) != null)
              {
                drawPanel.Cursor = Cursors.Cross;
              }
              else if (QGraphicsHelper.IsPointInObjects(QHelper.CurrentWorkQItem.selectedObjects, mapPoint) == true)
              {
                  drawPanel.Cursor = Cursors.SizeAll;
              }
              if (CheckAndDrawIfMouseOnLines(e.X, e.Y) == true)
              {
                  drawPanel.Cursor = Cursors.Cross;
              }
            }
            else if (e.Button == MouseButtons.Left)
            {
              if (currentMouseAction == MouseAction.MA_OnPoints)
              {
                drawPanel.Cursor = Cursors.Arrow;
                QHelper.ChangeAllPoints(QHelper.CurrentWorkQItem.selectedPoints.ToArray(), -deltaX, -deltaY);
              }
              else if (currentMouseAction == MouseAction.MA_OnObjects)
              {
                drawPanel.Cursor = Cursors.SizeAll;
                QHelper.ChangeAllPoints(QHelper.GetAllObjectsPoints(QHelper.CurrentWorkQItem.selectedObjects.ToArray()), -deltaX, -deltaY);
              }
              else if (currentMouseAction == MouseAction.MA_Selection)
              {
                selectionRect.Width -= deltaX;
                selectionRect.Height -= deltaY;
                drawPanel.Cursor = Cursors.Arrow;
              }
              else if (currentMouseAction == MouseAction.MA_OnLine)
              {
                drawPanel.Cursor = Cursors.Cross;
                QHelper.ChangeAllPoints(lastHighlightedLine, -deltaX, -deltaY);
              }

              RenderAll();
            }
           
            if (e.Button == MouseButtons.Middle)
            {
              drawPanel.Cursor = Cursors.SizeAll;
              QGraphicsHelper.ViewRect.Left += deltaX;
              QGraphicsHelper.ViewRect.Top += QGraphicsHelper.Preferences.TopOnBottom ? deltaY : -deltaY; ;

              RenderAll();
            }

            mousePreviousPos = new Point(e.X, e.Y);

            setStatusLabelInfo();
        }

        private void drawPanel_MouseUp(object sender, MouseEventArgs e)
        {
          if (currentMouseAction == MouseAction.MA_Selection)
          {
            if (selectionRect.Width != 0 && selectionRect.Height != 0)
            {
              FindSelectedObjects();
            }
          }
          if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
          {
              propertyGrid1.Refresh();
          }
            
          mousePreviousPos = new Point(0, 0);
          drawPanel.Cursor = Cursors.Arrow;
          selectionRect = QGraphicsHelper.NewQRectF(0, 0, 0, 0);
          currentMouseAction = MouseAction.MA_Nothing;

          RenderAll();
        }

        private void drawPanel_Resize(object sender, EventArgs e)
        {
          drawTo = drawPanel.CreateGraphics();
          tmpsurface = new Bitmap(drawPanel.Width, drawPanel.Height); ;
          currentOutput = Graphics.FromImage(tmpsurface);

          QGraphicsHelper.ViewRect = new QRectangleF()
          {
              Left = QGraphicsHelper.ViewRect.Left,
              Top = QGraphicsHelper.ViewRect.Top,
              Width = currentOutput.VisibleClipBounds.Width / QGraphicsHelper.ZoomAspect,
              Height = currentOutput.VisibleClipBounds.Height / QGraphicsHelper.ZoomAspect
          };
            
          if (comboBox1.SelectedItem != null)
          {
            QGraphicsHelper.NavigateToObject(comboBox1.SelectedItem as QObject);
          }
        }

        private void NewMap()
        {
          QHelper.CurrentWorkQItem = new QMapCollectorItem(new QMap(), 0, new List<QObject>(), new List<QPoint>());
          QHelper.CurrentMap.Layers.Add(new QMapLayer());
          QHelper.CurrentMap.Layers[0].Visible = true;
          QHelper.CurrentMap.Layers[0].Name = QbiconConstants.DEFAULT_QLAYER_NAME;
          QHelper.CurrentMap.Name = QbiconConstants.DEFAULT_QMAP_NAME;
          QHelper.ActiveLayerNum = 0;
          QHelper.CurrentWorkQItem.selectedObjects.Clear();
          QHelper.CurrentWorkQItem.selectedPoints.Clear();
            
          comboBox1.Items.Clear();
          drawPanel_Resize(null, null);
          QGraphicsHelper.NavigateToPoint(0, 0);
          SetActiveQObject(null);
          propertyGrid1.SelectedObject = QHelper.CurrentMap;
          FillLayersMenuFromCurrentMap();

          RenderAll();
        }

        private void FillLayersMenuFromCurrentMap()
        {
          if (QHelper.CurrentMap != null)
          {
            activeLayerMenuItem.DropDownItems.Clear();

            foreach (QMapLayer layer in QHelper.CurrentMap.Layers)
            {
              ToolStripMenuItem tsmi = new ToolStripMenuItem();
              tsmi.Name = layer.Name;
              tsmi.Text = layer.Name;

              if (layer.Name == QHelper.CurrentLayer.Name)
              {
                tsmi.Checked = true;
              }

              activeLayerMenuItem.DropDownItems.Add(tsmi);
            }
          }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewMap();
        }

        private void saveMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentMap == null)
          {
            return;
          }

          saveFileDialog1.Filter = string.Format("QMap file (*.{0}) |*.{0}", QbiconConstants.FILE_EXTENSION_QMAP);
          saveFileDialog1.Title = "Select new QMap file";
          saveFileDialog1.FileName = string.Format("{0}.{1}", QHelper.CurrentMap.Name, QbiconConstants.FILE_EXTENSION_QMAP);

          if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName.Length > 0)
          {
            QHelper.SaveQMap(saveFileDialog1.FileName, QHelper.CurrentMap);
          }
        }

        private void propertiesMenuItem_Click(object sender, EventArgs e)
        {
          propertyGrid1.SelectedObject = QHelper.CurrentMap;
        }

        private void loadMapMenuItem_Click(object sender, EventArgs e)
        {
          openFileDialog1.Title = "Select QMap file";
          openFileDialog1.Filter = string.Format("QMap file (*.{0}) |*.{0}", QbiconConstants.FILE_EXTENSION_QMAP);
          openFileDialog1.Multiselect = false;
          openFileDialog1.FileName = "";

          if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileNames.Length > 0)
          {
              QMap qmap = QHelper.LoadQMap(openFileDialog1.FileName);

              if (qmap != null)
              {
                QHelper.CurrentWorkQItem = new QMapCollectorItem(qmap, 0, new List<QObject>(), new List<QPoint>());
                comboBox1.Items.Clear();
                  
                propertyGrid1.SelectedObject = QHelper.CurrentMap;
                  
                if (QHelper.CurrentMap.Layers.Count > 0)
                {
                  QHelper.ActiveLayerNum = 0;
                  comboBox1.Items.AddRange(QHelper.CurrentLayer.Objects.ToArray());
                  FillLayersMenuFromCurrentMap();
                      
                  (activeLayerMenuItem.DropDownItems[0] as ToolStripMenuItem).Checked = true;
                }
                else
                {
                  FillLayersMenuFromCurrentMap();
                }
                  
                drawPanel_Resize(null, null);
                  
                if (QHelper.CurrentLayer != null)
                {
                  if (QHelper.CurrentLayer.Objects.Count > 0)
                  {
                      QGraphicsHelper.NavigateToObject(QHelper.CurrentLayer.Objects[0]);
                  }
                  else
                  {
                      QGraphicsHelper.NavigateToPoint(0, 0);
                  }
                 }
                 else
                 {
                   QGraphicsHelper.NavigateToPoint(0, 0);
                 }
                  
                 RenderAll();
                }
            }
        }

        private void newObjMenuItem_Click(object sender, EventArgs e)
        {
          Random r = new Random();

          QObject qob = QHelper.AddNewQObject(
              QbiconConstants.DEFAULT_QOBJECT_NAME,
              new TextureInfo() { KeyName = QbiconConstants.DEFAULT_QOBJECT_TEXTURE},
              Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)),
              QHelper.CreateNewPolygone(),
              true);

          QPoint pos = new QPoint()
          {
              X = QGraphicsHelper.ViewRect.Left + QGraphicsHelper.ViewRect.Width / 2,
              Y = QGraphicsHelper.ViewRect.Top+QGraphicsHelper.ViewRect.Height / 2 };

          if (QGraphicsHelper.Preferences.TopOnBottom == false)
          {
            pos.Y = -pos.Y;
          }

          if (qob != null)
          {
            QHelper.ChangeAllPoints(qob.Poly.Points.ToArray(), pos.X, pos.Y );
            comboBox1.Items.Add(qob);
            comboBox1.SelectedItem = qob;
            QHelper.CurrentWorkQItem.selectedObjects.Clear();
            QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
            QHelper.CurrentWorkQItem.selectedPoints.Clear();
            QHelper.CurrentWorkQItem.selectedPoints.AddRange(qob.Poly.Points.ToArray());
            QGraphicsHelper.NavigateToObject(qob);
          }
        }

        private void saveObjMenuItem_Click(object sender, EventArgs e)
        {
            QObject qob = comboBox1.SelectedItem as QObject;

            if (qob== null)
            {
                return;
            }

            saveFileDialog1.Filter = string.Format("QObject file |*.{0}", QbiconConstants.FILE_EXTENSION_QOBJECT);
            saveFileDialog1.Title = "Select new QObject file";
            saveFileDialog1.FileName = string.Format("{0}.{1}", qob.Name, QbiconConstants.FILE_EXTENSION_QOBJECT);

            if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName.Length > 0)
            {
              QHelper.SaveQObject(saveFileDialog1.FileName, qob);
            }
        }

        private void loadObjMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Select QObject file";
            openFileDialog1.Filter = string.Format("QObject file |*.{0}", QbiconConstants.FILE_EXTENSION_QOBJECT);
            openFileDialog1.Multiselect = true;
            openFileDialog1.FileName = "";

            if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileNames.Length > 0)
            {
                string lastQObjectName = string.Empty;

                if (comboBox1.SelectedItem != null)
                {
                  lastQObjectName = (comboBox1.SelectedItem as QObject).Name;
                }

                foreach (string fn in openFileDialog1.FileNames)
                {
                    QObject qObj = QHelper.LoadQObject(fn);

                    if (qObj != null)
                    {
                        string loadedName = QHelper.AddNewQObject(qObj);

                        if (loadedName.Length > 0)
                        {
                            lastQObjectName = loadedName;
                            comboBox1.Items.Add(lastQObjectName);
                        }
                    }
                }

                comboBox1.SelectedItem = lastQObjectName;
                FillLayersMenuFromCurrentMap();
            }
        }

        private void copyObjStripMenuItem_Click(object sender, EventArgs e)
        {
            List<QObject> newObjects = new List<QObject>();

            if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
            {
              foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
              {
                QObject q = QHelper.AddNewQObject(qob.Name,
                                      qob.Texture,
                                      qob.Color,
                                      qob.Poly,
                                      qob.Visible);

                QHelper.ChangeObjectPoints(q, 1, 1);
                comboBox1.Items.Add(q);
                newObjects.Add(q);
              }
            }

            if (newObjects.Count > 0)
            {
              QHelper.CurrentWorkQItem.selectedObjects.Clear();
              QHelper.CurrentWorkQItem.selectedObjects.AddRange(newObjects.ToArray());
              QHelper.CurrentWorkQItem.selectedPoints.Clear();
              QHelper.CurrentWorkQItem.selectedPoints.AddRange(QHelper.GetAllObjectsPoints(newObjects.ToArray()));
              comboBox1.SelectedItem = QHelper.CurrentWorkQItem.selectedObjects[0];
            }
        }
        
        private void removeObjMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
          {
            QMapCollector.Push(QHelper.CurrentWorkQItem);
            
            foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
            {
                comboBox1.Items.Remove(qob);
                QHelper.RemoveQObject(qob);
            }
              
            QHelper.CurrentWorkQItem.selectedObjects.Clear();
            QHelper.CurrentWorkQItem.selectedPoints.Clear();
            SetActiveQObject(comboBox1.SelectedItem as QObject);
          }
        }

        private void zoomInToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QGraphicsHelper.ChangeZoom(0.1f);

            if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
            {
                QGraphicsHelper.NavigateToObject(QHelper.CurrentWorkQItem.selectedObjects[0]);
            }

            RenderAll();
        }

        private void zoomOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QGraphicsHelper.ChangeZoom(-0.1f);

            if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
            {
                QGraphicsHelper.NavigateToObject(QHelper.CurrentWorkQItem.selectedObjects[0]);
            }

            RenderAll();
        }

        private void navigateToActiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QGraphicsHelper.NavigateToObject(comboBox1.SelectedItem as QObject);
        }

        private void sendToBackMenuItem_Click(object sender, EventArgs e)
        {
          foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
          {
            QHelper.SendObjectToBack(qob);
          }

          RenderAll();
        }

        private void sendToFrontMenuItem_Click(object sender, EventArgs e)
        {
          foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
          {
            QHelper.SendObjectToFront(qob);
          }

          RenderAll();
        }
       
        private void drawPanel_MouseClick(object sender, MouseEventArgs e)
        {
          if (e.Button == MouseButtons.Right)
          {
            Point rightClickIn = new Point(e.X, e.Y);
            QPoint mapPoint = QGraphicsHelper.GetPointOnMap(e.X, e.Y);
            QObject qob;

            if (CheckAndDrawIfMouseOnLines(e.X, e.Y)==true)
            {
              addPointMenuItem.Enabled = true;
              QHelper.CurrentWorkQItem.selectedPoints.Clear();
              QHelper.CurrentWorkQItem.selectedPoints.AddRange(lastHighlightedLine);
              RenderAll();
              pointsContextMenu.Show(drawPanel, rightClickIn);
              RenderAll();

              return;
            }

            QPoint qp = QGraphicsHelper.IsPointInCornerRects(QHelper.CurrentWorkQItem.selectedPoints.ToArray(), QGraphicsHelper.GetPointOnScreen(mapPoint));

            if (qp != null)
            {
              qob = QHelper.GetPointParentObject(qp);

              if (qob != null)
              {
                SetActiveQObject(qob);
                addPointMenuItem.Enabled = false;
                pointsContextMenu.Show(drawPanel, rightClickIn);

                RenderAll();
              }
            }
            else
            {
              qob = QGraphicsHelper.IsPointInCornersOfObjects(QHelper.CurrentWorkQItem.selectedObjects, e.X, e.Y);
              
              if (qob != null)
              {
                QHelper.CurrentWorkQItem.selectedPoints.Clear();
                QHelper.CurrentWorkQItem.selectedPoints.Add(mapPoint);
                SetActiveQObject(qob);
                addPointMenuItem.Enabled = false;
                pointsContextMenu.Show(drawPanel, rightClickIn);

                RenderAll();
              }
              else
              {
                qob = QGraphicsHelper.IsPointInObjects(QHelper.CurrentWorkQItem.selectedObjects, mapPoint.X, mapPoint.Y);
                
                if (qob != null)
                {
                  QHelper.CurrentWorkQItem.selectedPoints.Clear();
                  QHelper.CurrentWorkQItem.selectedPoints.AddRange(QHelper.GetAllObjectsPoints(QHelper.CurrentWorkQItem.selectedObjects.ToArray()));
                  SetActiveQObject(qob);
                  objectContextMenu.Show(drawPanel, rightClickIn);

                  RenderAll();
                }
                else
                {
                  QHelper.CurrentWorkQItem.selectedObjects.Clear();
                  QHelper.CurrentWorkQItem.selectedPoints.Clear();
                  qob = QGraphicsHelper.IsPointInCornersOfObjects(QHelper.CurrentLayer.Objects, e.X, e.Y);
                  
                  if (qob != null)
                  {
                    QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
                    QHelper.CurrentWorkQItem.selectedPoints.Add(QGraphicsHelper.IsPointInCornersOfObject(qob, e.X, e.Y));
                    addPointMenuItem.Enabled = false;
                    pointsContextMenu.Show(drawPanel, rightClickIn);
                    
                    RenderAll();
                  }
                  else
                  {
                    qob = QGraphicsHelper.IsPointInObjects(QHelper.CurrentLayer.Objects, mapPoint.X, mapPoint.Y);
                    
                    if (qob != null)
                    {
                      QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
                      QHelper.CurrentWorkQItem.selectedPoints.AddRange(qob.Poly.Points.ToArray());
                      objectContextMenu.Show(drawPanel, rightClickIn);

                      RenderAll();
                    }
                  }
                }
              }
            }
          }
        }

        private void drawPanel_MouseDoubleClick(object sender, MouseEventArgs e)
        {
          if (e.Button == MouseButtons.Left)
          {
            QPoint mapPoint = QGraphicsHelper.GetPointOnMap(e.X, e.Y);
            QObject qob;
            
            qob = QGraphicsHelper.IsPointInCornersOfObjects(QHelper.CurrentWorkQItem.selectedObjects, e.X, e.Y);
            
            if (qob != null)
            {
              QHelper.CurrentWorkQItem.selectedObjects.Clear();
              QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
              QHelper.CurrentWorkQItem.selectedPoints.Clear();
              QHelper.CurrentWorkQItem.selectedPoints.Add(QGraphicsHelper.IsPointInCornersOfObject(qob, e.X, e.Y));

              SetActiveQObject(qob);

              if (QHelper.CurrentWorkQItem.selectedPoints.Count > 0)
              {
                propertyGrid1.SelectedObject = QHelper.CurrentWorkQItem.selectedPoints[0];
              }
            }
            else
            {
              qob = QGraphicsHelper.IsPointInObjects(QHelper.CurrentWorkQItem.selectedObjects, mapPoint.X, mapPoint.Y);
              
              if (qob != null)
              {
                QHelper.CurrentWorkQItem.selectedObjects.Clear();
                QHelper.CurrentWorkQItem.selectedObjects.Add(qob);
                QHelper.CurrentWorkQItem.selectedPoints.Clear();
                QHelper.CurrentWorkQItem.selectedPoints.AddRange(qob.Poly.Points.ToArray());
                SetActiveQObject(qob);
              }
            }
          }

          currentMouseAction = MouseAction.MA_Nothing;
        }

        private void addPointMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentWorkQItem.selectedPoints.Count == 2)
          {
            QObject qob = QHelper.GetPointParentObject(QHelper.CurrentWorkQItem.selectedPoints[0]);
            QPoint qp = QHelper.CurrentWorkQItem.selectedPoints[1];
            int indx = qob.Poly.Points.IndexOf(qp);

            if (indx > -1)
            {
              QPoint np = new QPoint
                  {
                    X = qp.X + (QHelper.CurrentWorkQItem.selectedPoints[0].X - QHelper.CurrentWorkQItem.selectedPoints[1].X) / 2,
                    Y = qp.Y + (QHelper.CurrentWorkQItem.selectedPoints[0].Y - QHelper.CurrentWorkQItem.selectedPoints[1].Y) / 2
                  };

              QHelper.CurrentWorkQItem.selectedPoints.Clear();

              if (indx <= qob.Poly.Points.Count-2)
              {
                qob.Poly.Points.Insert(indx, np);
                QHelper.CurrentWorkQItem.selectedPoints.Add(qob.Poly.Points[indx]);
              }
              else
              {
                qob.Poly.Points.Add(np);
                QHelper.CurrentWorkQItem.selectedPoints.Add(qob.Poly.Points[qob.Poly.Points.Count - 1]);
              }
            }
          }
        }

      
        private void removePointsMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentWorkQItem.selectedPoints.Count > 0)
          {
            List<QObject> result = new List<QObject>(QHelper.CurrentWorkQItem.selectedObjects);

            foreach (QPoint qp in QHelper.CurrentWorkQItem.selectedPoints)
            {
              foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
              {
                if (qob.Poly.Points.Contains(qp) == true)
                {
                  qob.Poly.Points.Remove(qp);
                }
              }
            }

            QHelper.CurrentWorkQItem.selectedPoints.Clear();

            foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
            {
              if (qob.Poly.Points.Count == 0)
              {
                result.Remove(qob);
              }
            }

            QHelper.CurrentWorkQItem.selectedObjects = result;
          }
        }

        private void QForm_MouseWheel(object sender, MouseEventArgs e)
        {
          float delta = (float)((e.Delta / 120) * 0.1);

          if (currentWheelAction ==  WheelAction.MW_Zoom)
          {
            QGraphicsHelper.ChangeZoom(delta * 20);

            drawPanel_Resize(null, null);

            QPoint mp = QGraphicsHelper.GetPointOnMap(e.X, e.Y);
            QGraphicsHelper.NavigateToPoint(mp.X, mp.Y);
          }
          else if (currentWheelAction == WheelAction.MW_Scale)
          {
            QPoint[] points = QHelper.GetAllObjectsPoints(QHelper.CurrentWorkQItem.selectedObjects.ToArray());
            QPolygone p = new QPolygone();

            p.Points.AddRange(points);
            QGraphicsHelper.ScalePoly(p, delta * 11);
          }
          else if (currentWheelAction == WheelAction.MW_Rotate)
          {
            QPoint[] points = QHelper.GetAllObjectsPoints(QHelper.CurrentWorkQItem.selectedObjects.ToArray());
            QPolygone p = new QPolygone();

            p.Points.AddRange(points);
            QGraphicsHelper.RotatePoly(p, delta * 11);
          }

          RenderAll();
        }

       
        private void activeLayerMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
          int lindx = activeLayerMenuItem.DropDownItems.IndexOf(e.ClickedItem);

          QHelper.ActiveLayerNum = lindx;
          propertyGrid1.SelectedObject = QHelper.CurrentLayer;
          QHelper.CurrentWorkQItem.selectedObjects.Clear();
          QHelper.CurrentWorkQItem.selectedPoints.Clear();
          comboBox1.Items.Clear();
          comboBox1.Items.AddRange(QHelper.CurrentLayer.Objects.ToArray());

          //foreach (ToolStripItem tsi in activeLayerMenuItem.DropDownItems)
          //{
          //  (tsi as ToolStripMenuItem).Checked = false;
          //}
          //(e.ClickedItem as ToolStripMenuItem).Checked = true;
        }

        private void addLayerMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentMap != null)
          {
            QMapLayer ql = new QMapLayer();
            ql.Name = QHelper.FindFreeLayerName(QbiconConstants.DEFAULT_QLAYER_NAME);
            ql.Visible = true;
            QHelper.CurrentMap.Layers.Add(ql);
            QHelper.ActiveLayerNum = QHelper.CurrentMap.Layers.Count-1;
            propertyGrid1.SelectedObject = QHelper.CurrentLayer;
            comboBox1.Items.Clear();
            FillLayersMenuFromCurrentMap();
          }
        }

        private void removeLayerMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentMap != null)
          {
            if (QHelper.ActiveLayerNum != -1)
            {
              QHelper.CurrentMap.Layers.RemoveAt(QHelper.ActiveLayerNum);
              if (QHelper.CurrentMap.Layers.Count > 0)
              {
                QHelper.ActiveLayerNum = 0;
                propertyGrid1.SelectedObject = QHelper.CurrentLayer;
                FillLayersMenuFromCurrentMap();
                (activeLayerMenuItem.DropDownItems[0] as ToolStripMenuItem).Checked = true;
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(QHelper.CurrentLayer.Objects.ToArray());
              }
              else
              {
                QHelper.ActiveLayerNum = -1;
                propertyGrid1.SelectedObject = QHelper.CurrentMap;
                FillLayersMenuFromCurrentMap();
              }
            }

          }
        }

        #region TEXTURES
        private void addTextureToolStripMenuItem_Click(object sender, EventArgs e)
        {
          openFileDialog1.FileName = string.Empty;
          openFileDialog1.Filter = "Image Files (*.bmp, *.jpg, *.jpeg, *.png)|*.bmp;*.jpg;*.jpeg;*.png";
          openFileDialog1.Title = "Select texture file(s)";
          openFileDialog1.Multiselect = true;
          if (openFileDialog1.ShowDialog() == DialogResult.OK)
          {
            foreach (string fn in openFileDialog1.FileNames)
            {
              AddNewTexture(fn);
            }
          }
        }
        private void AddNewTexture(string fileName)
        {
          if (File.Exists(fileName) == true)
          {
            Image img = Image.FromFile(fileName);
            string key = Path.GetFileName(fileName);
            key = key.Replace(Path.GetExtension(fileName), string.Empty);
            key = FindFreeTextureKeyName(key);
            QGraphicsHelper.Textures.OriginalImages.Add(key, img);
            QGraphicsHelper.Textures.ThumbnailsList.Images.Add(key, img);
            this.texturesListView.Items.Add(key, key, key);
          }
        }
        private string FindFreeTextureKeyName(string name)
        {
          if (QGraphicsHelper.Textures.OriginalImages.Keys.Contains(name) == true)
          {
            for (int i = 0; i < int.MaxValue; i++)
            {
              name = String.Concat(name, i.ToString());
              if (QGraphicsHelper.Textures.OriginalImages.Keys.Contains(name) == false)
              {
                return name;
              }
            }
          }
          else
          {
            return name;
          }
          return string.Empty;
        }



        private void removeTextureToolStripMenuItem_Click(object sender, EventArgs e)
        {
          
          List<string> keys = new List<string>();
          foreach (ListViewItem lvi in texturesListView.SelectedItems)
          {
            keys.Add(lvi.Text);
            QGraphicsHelper.Textures.ThumbnailsList.Images.RemoveByKey(lvi.Text);
            QGraphicsHelper.Textures.OriginalImages.Remove(lvi.Text);
          }
          foreach (string key in keys)
          {
            texturesListView.Items.RemoveByKey(key);
          }

          
        }

        private void saveListToolStripMenuItem_Click(object sender, EventArgs e)
        {
          saveFileDialog1.FileName = string.Empty;
          saveFileDialog1.Filter = String.Format("Qbicon Textures List|*.{0}", QbiconConstants.FILE_EXTENSION_QIMAGELIST);
          saveFileDialog1.Title = "Selecte new textures list file";
          if (saveFileDialog1.ShowDialog() == DialogResult.OK)
          {
            QGraphicsHelper.Textures.Save(saveFileDialog1.FileName);
          }

        }

        private void loadListToolStripMenuItem_Click(object sender, EventArgs e)
        {
          openFileDialog1.FileName = string.Empty;
          openFileDialog1.Filter = String.Format("Qbicon Textures List|*.{0}", QbiconConstants.FILE_EXTENSION_QIMAGELIST);
          openFileDialog1.Title = "Selecte textures list file";
          openFileDialog1.Multiselect = false;
          if (openFileDialog1.ShowDialog() == DialogResult.OK)
          {
            QGraphicsHelper.Textures.Load(openFileDialog1.FileName);
            FillTexturesListView();
          }
        }

        private void FillTexturesListView()
        {
          texturesListView.Clear();
          foreach (string key in QGraphicsHelper.Textures.ThumbnailsList.Images.Keys)
          {
            texturesListView.Items.Add(key, key, key);
          }
        }

        private void activeLayerMenuItem_DropDownOpening(object sender, EventArgs e)
        {
          FillLayersMenuFromCurrentMap();
          
        }

        private void useTexturesMenuItem_Click(object sender, EventArgs e)
        {
          QGraphicsHelper.Preferences.UseTextures = !QGraphicsHelper.Preferences.UseTextures;
          useTexturesMenuItem.Checked = QGraphicsHelper.Preferences.UseTextures;

        }

        #endregion

        private void scaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
          scaleToolStripMenuItem.Checked = !scaleToolStripMenuItem.Checked;

          if (scaleToolStripMenuItem.Checked)
          {
            SetWheelAction(WheelAction.MW_Scale);
          }
          else
          {
            SetWheelAction(WheelAction.MW_Zoom);
          }
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
          propertyGrid1.SelectedObject = QGraphicsHelper.Preferences;
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
          saveFileDialog1.FileName = string.Empty;
          saveFileDialog1.Filter = String.Format("Qbicon Preferences|*.{0}", QbiconConstants.FILE_EXTENSION_QPREFERENCES);
          saveFileDialog1.Title = "Select new preferences file";

          if (saveFileDialog1.ShowDialog() == DialogResult.OK)
          {
            QHelper.SavePreferences(saveFileDialog1.FileName, QGraphicsHelper.Preferences);
          }
        }

        private void loadPrefMenuItem_Click(object sender, EventArgs e)
        {
          openFileDialog1.FileName = string.Empty;
          openFileDialog1.Filter = String.Format("Qbicon Preferences|*.{0}", QbiconConstants.FILE_EXTENSION_QPREFERENCES);
          openFileDialog1.Title = "Select textures list file";
          openFileDialog1.Multiselect = false;

          if (openFileDialog1.ShowDialog() == DialogResult.OK)
          {
            QPreferences prf = QHelper.LoadPreferences(openFileDialog1.FileName);
            if (prf != null)
            {
              QGraphicsHelper.Preferences = prf;
              propertyGrid1.SelectedObject = QGraphicsHelper.Preferences;
            }
          }
        }

        private void QForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                QHelper.SavePreferences("default.qpr", QGraphicsHelper.Preferences);
            }
            catch (IOException ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Unable To Save Preferences", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void texturesContextMenu_Opening(object sender, CancelEventArgs e)
        {
          setTextureMenuItem.Enabled = (texturesListView.SelectedItems.Count == 1 && QHelper.CurrentWorkQItem.selectedObjects.Count > 0);
        }

        private void SetTextureToObject(string tKey, QObject qob)
        {
          if (QGraphicsHelper.Textures.OriginalImages.Keys.Contains(tKey)==true)
          {
            qob.Texture.KeyName = tKey;

            qob.Texture.SourceRect = QGraphicsHelper.NewQRect(0, 0,
                                QGraphicsHelper.Textures.OriginalImages[tKey].Width,
                                QGraphicsHelper.Textures.OriginalImages[tKey].Height);
          }
        }

        private void setTextureMenuItem_Click(object sender, EventArgs e)
        {
          if (QHelper.CurrentWorkQItem.selectedObjects != null)
          {
            foreach (QObject qob in QHelper.CurrentWorkQItem.selectedObjects)
            {
              SetTextureToObject(texturesListView.SelectedItems[0].Text, qob);
            }
          }
        }

        private void loadTextMenuItem_Click(object sender, EventArgs e)
        {
          addTextureToolStripMenuItem_Click(sender, e);
        }

        private void remTextureMenuItem_Click(object sender, EventArgs e)
        {
          removeTextureToolStripMenuItem_Click(sender, e);
        }

        private void rotateToolStripMenuItem_Click(object sender, EventArgs e)
        {
          rotateToolStripMenuItem.Checked = !rotateToolStripMenuItem.Checked;

          if (rotateToolStripMenuItem.Checked)
          {
            SetWheelAction(WheelAction.MW_Rotate);
          }
          else
          {
            SetWheelAction(WheelAction.MW_Zoom);
          }
        }

        private void UndoChanges()
        {
          QMapCollectorItem previous = QMapCollector.Pop();

          if (previous != null)
          {
            QHelper.CurrentWorkQItem = previous;
          }

          comboBox1.Items.Clear();
          comboBox1.Items.AddRange(QHelper.CurrentLayer.Objects.ToArray());

          if (QHelper.CurrentWorkQItem.selectedObjects.Count > 0)
          {
            propertyGrid1.SelectedObject = QHelper.CurrentWorkQItem.selectedObjects[0];
          }

          RenderAll();
        }

      
        private void splitContainer1_KeyDown(object sender, KeyEventArgs e)
        {
          switch (e.KeyCode)
          {
              case Keys.Z:
            
                if (e.Control == true)
                {
                    UndoChanges();
                }
            
                break;
          }
        }
    }
}
